<?php

namespace App\Http\Controllers;

use App\Models\Championship;
use App\Models\ChampionshipUser;
use App\Models\WechatUser;
use Illuminate\Http\Request;

class ChampionshipUserController extends Controller
{
    public function signupList()
    {
        $championshipId = request()->input('id');
        $list = ChampionshipUser::where('championship_id', $championshipId)
            ->with('user:id,name,head_img,nickname')
            ->select('id', 'user_id')
            ->get();

        return response()->json(
            [
                'recode' => 1,
                'list' => $list,
            ]
        );

    }
    public function signup()
    {
        $championshipId = request()->input('championship');
        $userId = request()->input('user_id');

        //查询比赛信息
        $championshipInfo = Championship::find($championshipId);
        if ($championshipInfo == null || $championshipInfo->status != 20) {
            return response()->json(
                [
                    'recode' => 0,
                    'msg' => '未找到赛事',
                ]
            );
        }
        $now = date("Y-m-d H:i:s");
        if ($now > $championshipInfo->signup_datetime) {
            return response()->json(
                [
                    'recode' => 0,
                    'msg' => '报名已经截止',
                ]
            );

        }
        //查询用户
        $userInfo = WechatUser::find($userId);
        if ($userInfo == null) {
            return response()->json(
                [
                    'recode' => 0,
                    'msg' => '用户不存在',
                ]
            );
        }

        //查看用户是否已经报名
        $signupUser = ChampionshipUser::where([['championship_id', $championshipId], ['user_id', $userId]])->first();
        if ($signupUser) {
            return response()->json(
                [
                    'recode' => 0,
                    'msg' => '您已经报名',
                ]
            );
        }

        $championshipUser = new ChampionshipUser;
        $championshipUser->championship_id = $championshipId;
        $championshipUser->user_id = $userId;
        $championshipUser->status = 20;
        $championshipUser->save();

        return response()->json(
            [
                'recode' => 1,
                'msg' => '报名成功',
            ]
        );

    }
}
